import win32api
import win32gui
from win32con import WM_INPUTLANGCHANGEREQUEST
import time


def get_language():
    """获取当前输入法状态"""
    hwnd = win32gui.GetForegroundWindow()
    thread_id = win32api.GetWindowLong(hwnd, 0)
    klid = win32api.GetKeyboardLayout(thread_id)
    lid = klid & (2 ** 16 - 1)
    lid_hex = hex(lid)

    if lid_hex == '0x409':
        print('当前的输入法状态是英文输入模式\n\n')
        input_language = "EN"
    elif lid_hex == '0x804':
        print('当前的输入法是中文输入模式\n\n')
        input_language = "ZH"
    else:
        print('当前的输入法既不是英文输入也不是中文输入\n\n')
        input_language = "ZH"


def change_language(language="EN"):
    """
    切换语言
    :param language: EN––English; ZH––Chinese
    :return: bool
    """
    LANGUAGE = {
        "ZH": 0x0804,
        "EN": 0x0409
    }
    hwnd = win32gui.GetForegroundWindow()
    result = win32api.SendMessage(
        hwnd,
        WM_INPUTLANGCHANGEREQUEST,
        0,
        LANGUAGE[language]
    )
    print(result)
    if not result:
        return True


if __name__ == '__main__':
    # get_language()
    # time.sleep(3)
    change_language(language="ZH")
    # time.sleep(3)
    # change_language(language="EN")
